package com.iwhalecloud.bss.kite.cucc.web.service.accept.handler.module;

import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

import com.iwhalecloud.bss.kite.client.dto.DataResult;
import com.iwhalecloud.bss.kite.common.constant.ServiceOfferConsts;
import com.iwhalecloud.bss.kite.cucc.client.api.goods.IGoodsService;
import com.iwhalecloud.bss.kite.cucc.client.dto.goods.GoodPriceAttrReqDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.goods.GoodPriceReqDTO;
import com.iwhalecloud.bss.kite.cucc.common.util.StrTools;
import com.iwhalecloud.bss.kite.manager.enums.InstType;
import com.iwhalecloud.bss.kite.manager.inst.KiteProdInst;
import com.iwhalecloud.bss.kite.manager.inst.KiteSceneInst;
import com.iwhalecloud.bss.kite.service.scene.attr.OperateInstAttrService;
import com.ztesoft.bss.base.staticdata.ServiceOfferConst;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.common.collect.Lists;
import com.iwhalecloud.bss.kite.client.vo.scene.ModuleVO;
import com.iwhalecloud.bss.kite.client.vo.scene.ProdAttrModuleVO;
import com.iwhalecloud.bss.kite.client.vo.scene.ProdAttrVO;
import com.iwhalecloud.bss.kite.client.vo.scene.ProdRoleModuleVO;
import com.iwhalecloud.bss.kite.client.vo.scene.ProductModuleVO;
import com.iwhalecloud.bss.kite.common.constant.KeyConsts;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.client.vo.scene.SceneNewOfferSeneVO;
import com.iwhalecloud.bss.kite.cucc.client.vo.scene.ServiceOfferInfoModuleVO;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalKeyConsts;
import com.iwhalecloud.bss.kite.cucc.service.goods.GoodsHelper;
import com.iwhalecloud.bss.kite.dataservice.cache.DcPublicCache;
import com.iwhalecloud.bss.kite.dataservice.cache.OfferCache;
import com.iwhalecloud.bss.kite.dataservice.entity.spec.Offer;
import com.iwhalecloud.bss.kite.manager.api.IOperateSceneInstService;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttr;
import com.iwhalecloud.bss.kite.manager.inst.KiteOfferInst;
import com.iwhalecloud.bss.kite.web.service.accept.bo.AcceptContext;
import com.iwhalecloud.bss.kite.web.service.accept.bo.SceneModule;

import com.ztesoft.bss.common.util.SpringUtil;

/**
 * <Description> <br>
 * 产品组件处理类 1.销售品根据产品类型分类
 *
 * @author zhu.zixin<br>
 * @version 1.0<br>
 */
@Service
public class LocalProductModuleHandler extends LocalAbstractProductModuleHandler {

    @Autowired
    IQuerySceneInstService querySceneInstService;

    @Autowired
    IOperateSceneInstService operateSceneInstService;

    @Autowired
    private IGoodsService goodsService;

    @Override
    public List<? extends ModuleVO> execute(AcceptContext context, SceneModule sceneModule) {

        List<ProductModuleVO> productModuleList = getViewSceneVo("main", context);
        productModuleList.removeIf(product -> KiteStringUtils.equals(OfferCache.get(product.getOfferId()).getCateId(), "2004010"));
        ((SceneNewOfferSeneVO) context.getSceneVo()).getSceneProductModuleVO().setProduct(productModuleList);

        List<ProductModuleVO> productModuleVOList = ((SceneNewOfferSeneVO) context.getSceneVo()).getSceneProductModuleVO().getProduct();
        ServiceOfferInfoModuleVO serviceOfferInfoModel = ((SceneNewOfferSeneVO) context.getSceneVo()).getServiceOfferInfoModuleVO();
        KiteSceneInst sceneInst = querySceneInstService.getSceneInst(context.getSceneVo().getSceneInstId());
        KiteOfferInst offerInst = querySceneInstService.getOfferInst(context.getAcceptRequest().getCustId(), sceneInst.getRootInstId());
        //String objId = OfferCache.get(offerInst.geta).getAttrValue("cateId");
        String cateId = offerInst.getAttrValue("cateId");
        boolean isRhChange = KiteStringUtils.equalsAny(cateId, DcPublicCache.getCodeb("210728701", "wlwCate").split(","))&&Objects.equals(InstType.GIFT_OFFER_INST, sceneInst.getRootInstType())&&KiteStringUtils.isNotEmpty(sceneInst.getServiceOfferId())&&KiteStringUtils.equals(ServiceOfferConst.service_offer_2826,sceneInst.getServiceOfferId());
        // 业务变更存在操作类型模块的，产品属性不能编辑  新增融合变更时非接入类产品属性不可编辑
        if ((Objects.nonNull(serviceOfferInfoModel) && KiteListUtils.isNotEmpty(serviceOfferInfoModel.getServiceOfferTypes()))||isRhChange) {
            productModuleVOList.forEach(productModuleVO ->{
                Offer offer = null;
                if(isRhChange) {
                    offer = OfferCache.get(productModuleVO.getOfferId());
                }
                if((!isRhChange)||(Objects.nonNull(offer)&&KiteStringUtils.equals(offer.getAttrValue("cateId"),"2000961"))) {
                    productModuleVO.getProdRole().forEach(prodRole -> {
                        prodRole.getProdAttr().getProdAttrList().forEach(prodAttr -> {
                            prodAttr.setIsEdit(KeyConsts.IFTRUE_F);
                            if (KiteStringUtils.isEqual(prodAttr.getIsEditImg(), KeyConsts.IFTRUE_T)) {
                                prodAttr.setIsEditImg(KeyConsts.IFTRUE_F);
                            }
                        });
                    });
                }
            });
        }

        // SDWAN非订购操作，因用户中心不落标准月租，初始化标准月租为空，调接口查询标准月租值
        this.setSDWANProductAttr(productModuleVOList, context.getAcceptRequest().getServiceOfferId(), context.getAcceptRequest().getSceneInstId());

        // 对产品属性进行分组
        divideProdAttr(productModuleVOList, context.getAcceptRequest().getSceneInstId(),
            context.getAcceptRequest().getCustId(), false);
        return productModuleVOList;
    }

    @Override
    public List<? extends ModuleVO> previewSceneVo(AcceptContext context, SceneModule sceneModule) {
        List<ProductModuleVO> productModuleList = getViewSceneVo("main", context);
        productModuleList.removeIf(product -> KiteStringUtils.equals(OfferCache.get(product.getOfferId()).getCateId(), "2004010"));
        ((SceneNewOfferSeneVO) context.getSceneVo()).getSceneProductModuleVO().setProduct(productModuleList);

        List<ProductModuleVO> productList = ((SceneNewOfferSeneVO) context.getSceneVo()).getSceneProductModuleVO().getProduct();
        // 追加配件时，页面不展示没有实物附加商品的成员商品
        if (KiteStringUtils.isEqual("2020", context.getAcceptRequest().getServiceOfferId())) {
            productList.removeIf(productModuleVO -> !GoodsHelper.containMaterialOffer(productModuleVO.getOfferId()));
        }
        if (KiteListUtils.isEmpty(productList)) {
            return productList;
        }
        for (ProductModuleVO product : productList) {
            List<ProdRoleModuleVO> prodRoleModuleList = product.getProdRole();
            if (KiteListUtils.isEmpty(prodRoleModuleList)) {
                continue;
            }
            product.setIsEdit(LocalKeyConsts.IFTRUE_F);
            for (ProdRoleModuleVO prodRoleModule : prodRoleModuleList) {
                ProdAttrModuleVO prodAttrModule = prodRoleModule.getProdAttr();
                List<ProdAttrVO> prodAttrList = prodAttrModule.getProdAttrList();
                Iterator<ProdAttrVO> iterator = prodAttrList.iterator();
                while (iterator.hasNext()) {
                    ProdAttrVO prodAttr = iterator.next();
                    if (KeyConsts.PROD_ATTR_SHOW_TYPE_E.equals(prodAttr.getShowType())) {
                        // 过滤隐藏的产品属性
                        iterator.remove();
                    }
                    else {
                        // 98H的不修改,避免后续属性分组处理时把98H的放到了formAttrList中（定制类-资费计划）
                        if (KeyConsts.GEN_LOGIC.equals(prodAttr.getAttrValueTypeId())) {
                            continue;
                        }
                        prodAttr.setAttrValueTypeId(LocalKeyConsts.ATTRVALUE_TT);
                    }
                }
            }
        }
        // 预览页面展示新旧值处理
        dealPreviewOldAndNewValues(productList, context.getAcceptRequest().getSceneInstId());
        // 对产品属性进行分组
        divideProdAttr(productList, context.getAcceptRequest().getSceneInstId(), context.getAcceptRequest().getCustId(), true);

        return ((SceneNewOfferSeneVO) context.getSceneVo()).getSceneProductModuleVO().getProduct();
    }

    @Override
    public List<? extends ModuleVO> executeChange(AcceptContext context, SceneModule sceneModule) {
        return this.previewSceneVo(context, sceneModule);
    }

    @Override
    public List<? extends ModuleVO> previewChangeSceneVo(AcceptContext context, SceneModule sceneModule) {
        return this.previewSceneVo(context, sceneModule);
    }





    /**
     * SDWAN非订购操作，因用户中心不落标准月租，初始化标准月租为空，调接口查询标准月租值
     * @author zhang.song
     * @date 2021-06-25 16:22
     * @param productModuleVOList
     * @param serviceOfferId
     * @param sceneInstId
     * @return void
     */
    private void setSDWANProductAttr(List<ProductModuleVO> productModuleVOList, String serviceOfferId, String sceneInstId) {
        if(KiteListUtils.isEmpty(productModuleVOList) || Objects.isNull(productModuleVOList.get(0))
            || KiteStringUtils.isEmpty(productModuleVOList.get(0).getOfferId())) {
            return;
        }

        // 非订购，初始化标准月租为空，调接口查询标准月租值
        if(!KiteStringUtils.equals(serviceOfferId, ServiceOfferConsts.SERVICE_OFFER_ORDER)) {
            String cateId = Optional.ofNullable(OfferCache.get(productModuleVOList.get(0).getOfferId())).map(Offer::getCateId).orElse("");
            if(KiteStringUtils.equals(cateId, "2101120")) {
                // 标准月租（元）
                String fieldName = "200001354";
                List<KiteProdInst> prodInsts = querySceneInstService.listProdInsts(sceneInstId);
                OperateInstAttrService operateInstAttrService = SpringUtil.getBean(OperateInstAttrService.class);

                productModuleVOList.forEach(productModuleVO -> {
                    productModuleVO.getProdRole().forEach(prodRole -> {
                        ProdAttrVO prodAttrVO = prodRole.getProdAttr().getProdAttrList().stream().filter(prodAttr -> KiteStringUtils.equals(prodAttr.getFieldName(), fieldName)).findAny().orElse(null);
                        if(Objects.nonNull(prodAttrVO) && KiteStringUtils.isEmpty(prodAttrVO.getValue())) {
                            KiteProdInst kiteProdInst = prodInsts.stream().filter(prodInst -> KiteStringUtils.equals(prodInst.getProdInstId(), prodRole.getProdInstId())).findAny().orElse(prodInsts.get(0));

                            // 获取关键属性值，查标准月租
                            List<GoodPriceAttrReqDTO> propertyValue = Lists.newArrayList();
                            kiteProdInst.getAttrMap().forEach((key, kiteAttr) -> {
                                if(KiteStringUtils.equals(kiteAttr.getMakeField(), "T")) {
                                    GoodPriceAttrReqDTO goodPriceAttrReq = new GoodPriceAttrReqDTO();
                                    goodPriceAttrReq.setAttr(kiteAttr.getFieldName());
                                    goodPriceAttrReq.setAttrVal(kiteAttr.getValue());
                                    propertyValue.add(goodPriceAttrReq);
                                }
                            });

                            GoodPriceReqDTO goodPriceReq = new GoodPriceReqDTO();
                            goodPriceReq.setSKU("10003406");
                            goodPriceReq.setPropertyValue(propertyValue);
                            // 查询价格
                            DataResult<String> result = goodsService.queryGoodPrice(goodPriceReq);
                            String price = result.getResultObject();
                            if(StrTools.isFloat(price)) {
                                prodAttrVO.setValue(price);

                                KiteAttr kiteAttr = kiteProdInst.getAttr(fieldName);
                                if(Objects.nonNull(kiteAttr)) {
                                    kiteAttr.setOriginValue(price);
                                    operateInstAttrService.setAttrValue(kiteProdInst, kiteAttr.getFieldName(), price, sceneInstId, null);
                                }
                            }
                        }
                    });
                });
            }
        }
    }
}
